﻿using RndMaterialDisposalService.Attrbutes;
using RndMaterialDisposalService.Controllers;
using RndMaterialDisposalService.Models;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using Microsoft.AspNetCore.Mvc.ModelBinding;
using Microsoft.AspNetCore.Mvc.RazorPages;
using System.Diagnostics;
using System.Reflection;

namespace RndMaterialDisposalService.Extensions
{
    /// <summary>
    /// 
    /// </summary>
    public class ApiResultResponseFilter:ActionFilterAttribute
    {
        private readonly ILogger<ApiResultResponseFilter> logger;
        /// <summary>
        /// 
        /// </summary>
        /// <param name="_logger"></param>
        public ApiResultResponseFilter(ILogger<ApiResultResponseFilter> _logger)
        {
            logger = _logger;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        public override void OnResultExecuting(ResultExecutingContext context)
        {
            //if (context.ModelState.ErrorCount > 0)
            //{
            //    var keys = context.ModelState.Where(p => p.Value!.ValidationState == ModelValidationState.Invalid).Select(p => p.Key);
            //    throw new Exception($"{string.Join(",", keys)} params invalid");
            //}

            if (context.ActionDescriptor.GetType().FullName == "Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor") {
                var customAttributeList = ((Microsoft.AspNetCore.Mvc.Controllers.ControllerActionDescriptor)context.ActionDescriptor).MethodInfo.CustomAttributes;
                foreach (var customAttribute in customAttributeList)
                {
                    Console.WriteLine(customAttribute.AttributeType.FullName);
                }
                if (!customAttributeList.Where(p => p.AttributeType.FullName == typeof(PageListAttribute).FullName).Any())
                {
                    var result = context.Result as ObjectResult;
                    context.Result = new OkObjectResult(ApiResponse<object>.Success(result?.Value ?? ""));
                }
            }

        }
    }
}
